<template>
	<div class="content">
		<el-form  size="default"  ref="ruleFormRef" :rules="rules" class="userInfoContent" :model="form" label-width="auto" style="max-width: 600px">
			<el-row :gutter="20">
				<el-col span="12">
					<el-form-item label="角色名称" prop="roleName">
					  <el-input v-model="form.roleName" />
					</el-form-item>
				</el-col>
				<el-col  span="12">
					<el-form-item label="角色标识" prop="roleMark">
					  <el-input v-model="form.roleMark" autofocus/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col span="12">
					<el-form-item label="排序" prop="sort">
					  <el-input v-model="form.sort" type="number" min="0"/>
					</el-form-item>
				</el-col>
				<el-col  span="12">
					<el-form-item label="状态" prop="status">
					  <el-radio-group v-model="form.status">
					    <el-radio value="1">正常</el-radio>
					    <el-radio value="0">禁止</el-radio>
					  </el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="菜单权限">
			  <el-checkbox-group v-model="form.menuIds">
			      <el-checkbox label="展开/折叠" value="0" @change="expendFun"/>
			      <el-checkbox label="全选/全不选" value="1" @change="selectFun"/>
			      <el-checkbox label="父子联动" value="2" @change="parentAndChildRealate"/>
			    </el-checkbox-group>
			</el-form-item>
			<el-row>
				<el-col>
					<el-form-item label="&nbsp;">
					    <el-tree
                  style="width: 100%;border:1px solid darkgray;font-size: 12px;"
					       :data="data"
						   :props="props"
					       show-checkbox
						   node-key="id"
						   :default-expand-all="toggleExpend"
						   :key="treeKey"
						   :default-checked-keys="checkKeys"
						   :check-strictly="parentAndChildRealateValue"
						   @check-change="checkChange"
					     />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</div>
  <div>
    <el-button round  size="default"   plain icon="Edit"  style="margin-left:180px;border-color: white;margin-right:20px;" type="primary" @click="onSubmit(ruleFormRef)">保存</el-button>
    <el-button round  size="default"  plain icon="Refresh"  style="color: darkgray;margin-right:20px;"  @click="resetForm(ruleFormRef)" >重置</el-button>
    <el-button round  size="default"  plain type="info"  @click="close" >取消</el-button>
  </div>
</template>

<script lang="ts" setup>
	import { nextTick, onMounted, reactive,ref ,computed,onUnmounted, watchEffect} from 'vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import { ElTree,ElMessage } from 'element-plus'; // 确保是从element-plus正确引入的
	import type Node from 'element-plus/es/components/tree/src/model/node'
	import {save} from '@/api/role.ts'
	import {treelist} from '@/api/menu.ts'
	import type { RefSymbol } from '@vue/reactivity';
	const emit = defineEmits(['closeAddRoleForm','success'])
	interface RuleForm {
	  roleName: string
	  roleMark: string,
	  sort:string,
	  status:string,
	  menuIds:Array<Number>
	}
	const ruleFormRef = ref<FormInstance>()
	const form = reactive<RuleForm>({
	  roleName: '',
	  roleMark: '',
	  sort:'0',
	  status:'1',
	  menuIds: [],
	})
	const rules = reactive<FormRules<RuleForm>>({
		roleName:[{required:true,message:'角色名称不能为空',trigger:'blur'}],
		roleMark:[{required:true,message:'角色标识不能为空',trigger:'blur'}]
	})
	
	
	const onSubmit = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.validate(async(valid, fields) => {
	    if (valid) {
		  form.menuIds = checkKeys.value
		  const {code} = await save(form);
		  if(code === 200){
		  	ElMessage({
		  	  type: 'success',
		  	  message: '新增成功',
		  	})
		  	emit('success')
			resetForm(ruleFormRef.value);
			treeKey.value= +new Date();
			checkKeys.value = []
		  }
	    } else {
	      console.log('error submit!', fields)
	    }
	  })
	}
	
	const resetForm = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.resetFields()
	}
	const close = ()=>{
		 treeKey.value= +new Date();
		 checkKeys.value = []
		 resetForm(ruleFormRef.value);
		 emit('closeAddRoleForm')
	}
	interface Tree{
		id: number
		label: string
		children?: Tree[]
	}
	const props={
		children: 'children',
		label: 'label',
		value:'value',
		id:'id'
	}
	const data = ref([])
	const menuData = ()=>{
		treelist().then((res)=>{
			if(res.code === 200){
				data.value=res.data;
			}
		})
	}
	onMounted(()=>{
		menuData();
	})
	
	
	const toggleExpend = ref(false);
	const treeKey = ref();
	const expendFun= ()=>{
		treeKey.value= +new Date();
		toggleExpend.value = !toggleExpend.value;
	}
	const checkKeys = ref([]);
	const selectFun = () =>{
		treeKey.value= +new Date();
		if(checkKeys.value.length > 0){
			checkKeys.value = []
		}else{
			const idKeys = ref([]);
			getId(idKeys.value,data.value)
			checkKeys.value = idKeys.value
		}
	}
	const getId=(idKeys:Array<number>,data:Array<object>)=>{
		data.forEach((item)=>{
			idKeys.push(item.id)
			if(item.children.length > 0){
				getId(idKeys,item.children);
			}
		})
	}
	const parentAndChildRealateValue= ref(true);
	const parentAndChildRealate =()=>{
		treeKey.value= +new Date();
		parentAndChildRealateValue.value = !parentAndChildRealateValue.value;
	}
	const checkChange = (data: any, checked: any, indeterminate: any) => {
	  console.log(data, checked, indeterminate);
	  if(checked === true && !checkKeys.value.includes(data.id)){
		  checkKeys.value.push(data.id)
		  if(checkKeys.value.indexOf(data.parentId) == -1){
				checkKeys.value.push(data.parentId)
		  }
	  }else if(checked === false && checkKeys.value.includes(data.id)){
	  	  checkKeys.value.splice(checkKeys.value.indexOf(data.id), 1); 
	  }
	}
</script>

<style scoped>
	.content{
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.userInfoContent{
		/* background-color: red; */
	}
</style>